let activeEffect = undefined;
function cleanup(effectFn) {
  for (let i = 0; i < effectFn.deps.length; i++) {
    let deps = effectFn.deps[i];
    deps.delete(effectFn);
  }
  effectFn.deps.length = 0;
}
function effect(fn) {
  const effectFn = () => {
    debugger;
    cleanup(effectFn);
    activeEffect = effectFn;
    fn();
  };
  effectFn.deps = [];
  effectFn();
}
const bucket = new WeakMap();
function track(target, key) {
  if (!activeEffect) return target[key];
  let depsMap = bucket.get(target);
  if (!depsMap) {
    bucket.set(target, (depsMap = new Map()));
  }
  let deps = depsMap.get(key);
  if (!deps) {
    depsMap.set(key, (deps = new Set()));
  }
  deps.add(activeEffect);
  activeEffect.deps.push(deps);
  console.log("get=bucket==", bucket);
  console.log("get=activeEffect==", activeEffect, activeEffect.deps);
}
function trigger(target, key) {
  const depsMap = bucket.get(target);
  if (!depsMap) return;

  const effects = depsMap.get(key);
  const effectsRun = new Set(effects);
  effectsRun && effectsRun.forEach((fn) => fn());
}
const obj = { ok: true, text: "hello" };
const objProxy = new Proxy(obj, {
  get(target, key, receiver) {
    console.log("key==", key);
    track(target, key);
    return target[key];
  },
  set(target, key, val, receiver) {
    target[key] = val;
    trigger(target, key);
    return true;
  },
});

// 当字段objProxy.ok的时候发生变化的时候，代码执行的分支也会跟着变化，这就是所谓的分支切换
effect(() => {
  console.log("effect", objProxy.ok ? objProxy.text : "not");
});

setTimeout(() => {
  objProxy.ok = false;
}, 1000);
